<template>
  <div class="layout-container">
    <!-- 页面选择器 -->
    <div class="page-selector mb-4">
      <el-card class="selector-card">
        <div class="selector-content">
          <div class="selector-title">页面布局编辑器</div>
          <el-radio-group v-model="currentPage" @change="handlePageChange" size="large">
            <el-radio-button v-for="page in pageOptions" :key="page.value" :label="page.value" :disabled="isSaving">
              {{ page.label }}
            </el-radio-button>
          </el-radio-group>
          <el-button type="primary" class="save-btn" @click="saveCurrentLayout" :loading="isSaving" size="large">
            <el-icon class="mr-1">
              <DocumentAdd />
            </el-icon>
            {{ isSaving ? '保存中...' : '保存布局' }}
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 视图模式切换 -->
    <div class="view-mode-selector mb-4">
      <el-radio-group v-model="viewMode" size="small">
        <el-radio-button label="all">全部卡片</el-radio-button>
        <el-radio-button label="visible">仅显示</el-radio-button>
        <el-radio-button label="hidden">仅隐藏</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 布局编辑器 -->
    <div class="layout-editor" v-loading="loading">
      <div class="empty-layout" v-if="filteredLayoutItems.length === 0">
        <el-empty description="暂无卡片" :image-size="200">
          <!-- <el-button type="primary" @click="addNewCard">添加新卡片</el-button> -->
        </el-empty>
      </div>
      <grid-layout v-else v-model:layout="filteredLayoutItems" :col-num="12" :row-height="30" :is-draggable="!isSaving"
        :is-resizable="!isSaving" :vertical-compact="true" :use-css-transforms="true" :margin="[10, 10]"
        @layout-updated="handleLayoutUpdate" class="grid-layout">
        <grid-item v-for="item in filteredLayoutItems" :key="item.i" :x="item.x" :y="item.y" :w="item.w" :h="item.h"
          :i="item.i" :min-w="2" :min-h="2" drag-allow-from=".drag-handle" :static="item.static || isSaving">
          <el-card shadow="hover" class="item-card" :class="{
            'static-item': item.static,
            'hidden-item': item.statedel === '1',
            'visible-item': item.statedel === '0'
          }">
            <template #header>
              <div class="drag-handle">
                <div class="item-header">
                  <span class="item-title">
                    <el-icon v-if="item.statedel === '1'" class="mr-1">
                      <Hide />
                    </el-icon>
                    <el-icon v-else class="mr-1">
                      <View />
                    </el-icon>
                    {{ item.remark || '卡片 ' + item.i }}
                  </span>
                  <div class="item-actions">
                    <el-tooltip content="切换显示/隐藏" placement="top">
                      <el-button :type="item.statedel === '0' ? 'success' : 'info'" circle
                        @click.stop="toggleCardVisibility(item)">
                        <el-icon v-if="item.statedel === '0'">
                          <View />
                        </el-icon>
                        <el-icon v-else>
                          <Hide />
                        </el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="编辑卡片" placement="top">
                      <el-button type="primary" circle @click.stop="editCard(item)">
                        <el-icon>
                          <Edit />
                        </el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="删除卡片" placement="top">
                      <el-button type="danger" circle @click.stop="deleteCard(item)">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </template>
            <div class="item-content">
              <div class="item-info">
                <div class="info-row">
                  <el-tag size="small" class="info-tag">ID: {{ item.i }}</el-tag>
                  <el-tag size="small" :type="item.statedel === '0' ? 'success' : 'info'" class="info-tag">
                    {{ item.statedel === '0' ? '显示' : '隐藏' }}
                  </el-tag>
                  <el-tag v-if="item.static" size="small" type="warning" class="info-tag">固定位置</el-tag>
                </div>
                <div class="info-row mt-2">
                  <div class="item-pos">
                    <el-tooltip content="卡片位置和尺寸" placement="top">
                      <el-tag size="small" effect="plain" class="position-tag">
                        <el-icon class="mr-1">
                          <Location />
                        </el-icon>
                        位置: ({{ item.x }}, {{ item.y }}) 尺寸: {{ item.w }}×{{ item.h }}
                      </el-tag>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </grid-item>
      </grid-layout>
    </div>

    <!-- 卡片编辑对话框 -->
    <card-editor-dialog v-model="editDialogVisible" :form-data="editForm" @confirm="saveCardEdit" />

    <!-- 添加卡片按钮 -->
    <!-- <el-button type="primary" circle icon="Plus" class="add-card-btn" @click="addNewCard" :disabled="isSaving" /> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  listLayoutConfig,
  addLayoutConfig,
  updateLayoutConfig,
  delLayoutConfig,
  batchUpdateLayoutConfig
} from "@/api/bk/LayoutConfig";
import CardEditorDialog from './CardEditorDialog.vue';
import {
  DocumentAdd,
  Edit,
  Delete,
  View,
  Hide,
  Location
} from '@element-plus/icons-vue';

// 配置信息
const pageOptions = ref([
  { value: 'aboutview', label: '关于页面' },
  { value: 'home', label: '首页' },
  { value: 'dashboard', label: '仪表盘' }
]);

// 响应式状态
const currentPage = ref('aboutview');
const layoutItems = ref([]);
const loading = ref(false);
const isSaving = ref(false);
const editDialogVisible = ref(false);
const viewMode = ref('all');
const editForm = reactive({
  id: null,
  i: '',
  remark: '',
  statedel: '0',
  static: false
});
let currentEditItem = null;

// 生命周期钩子
onMounted(() => {
  loadPageLayout(currentPage.value);
});

// 计算属性
const filteredLayoutItems = computed(() => {
  if (viewMode.value === 'all') {
    return layoutItems.value;
  } else if (viewMode.value === 'visible') {
    return layoutItems.value.filter(item => item.statedel === '0');
  } else {
    return layoutItems.value.filter(item => item.statedel === '1');
  }
});

// 方法实现
const loadPageLayout = async (page) => {
  try {
    loading.value = true;
    const response = await listLayoutConfig({ page, pageSize: 100 });

    layoutItems.value = processLayoutData(response.rows, page);
    ElMessage.success('布局加载成功');
  } catch (error) {
    console.error('加载布局失败:', error);
    ElMessage.error('加载布局失败');
    layoutItems.value = createDefaultLayout(page);
  } finally {
    loading.value = false;
  }
};

const processLayoutData = (data, page) => {
  if (!data || data.length === 0) return createDefaultLayout(page);

  return data.map(item => ({
    id: item.id,
    x: Number(item.x) || 0,
    y: Number(item.y) || 0,
    w: Number(item.w) || 4,
    h: Number(item.h) || 4,
    i: item.i || String(item.id),
    remark: item.remark || `卡片 ${item.id}`,
    page: item.page || page,
    statedel: item.statedel || '0',
    static: Boolean(item.static)
  }));
};

const createDefaultLayout = (page) => [
  { x: 0, y: 0, w: 6, h: 5, i: '1', remark: '欢迎卡片', page, statedel: '0' },
  { x: 6, y: 0, w: 6, h: 4, i: '2', remark: '功能卡片', page, statedel: '0' }
];

const handlePageChange = (page) => {
  ElMessageBox.confirm('切换页面将丢失未保存的修改，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    currentPage.value = page;
    loadPageLayout(page);
  }).catch(() => {
    // 恢复原选项
    currentPage.value = currentPage.value;
  });
};

const handleLayoutUpdate = () => {
  ElMessage({
    message: '布局已更新，记得保存哦',
    type: 'info',
    duration: 1500
  });
};

const editCard = (item) => {
  currentEditItem = item;
  Object.assign(editForm, {
    id: item.id,
    i: item.i,
    remark: item.remark,
    statedel: item.statedel,
    static: item.static
  });
  editDialogVisible.value = true;
};

const saveCardEdit = async (formData) => {
  try {
    const targetItem = layoutItems.value.find(item => item.i === currentEditItem.i);
    if (!targetItem) return;

    Object.assign(targetItem, formData);

    if (targetItem.id) {
      await updateLayoutConfig(targetItem);
    } else {
      const res = await addLayoutConfig(targetItem);
      targetItem.id = res.data.id;
    }

    ElMessage.success('卡片保存成功');
    editDialogVisible.value = false;
  } catch (error) {
    console.error('保存卡片失败:', error);
    ElMessage.error('保存卡片失败');
  }
};

const toggleCardVisibility = async (item) => {
  try {
    const newStateVal = item.statedel === '0' ? '1' : '0';
    const stateText = newStateVal === '0' ? '显示' : '隐藏';
    const targetItem = layoutItems.value.find(i => i.i === item.i);

    if (!targetItem) return;

    targetItem.statedel = newStateVal;

    if (targetItem.id) {
      await updateLayoutConfig(targetItem);
      ElMessage.success(`卡片已设为${stateText}`);
    }
  } catch (error) {
    console.error('切换卡片状态失败:', error);
    ElMessage.error('切换卡片状态失败');
    // 恢复原状态
    item.statedel = item.statedel === '0' ? '1' : '0';
  }
};

const deleteCard = async (item) => {
  try {
    await ElMessageBox.confirm(`确定删除卡片 "${item.remark || item.i}"？`, '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    });

    if (item.id) await delLayoutConfig(item.id);
    layoutItems.value = layoutItems.value.filter(i => i.i !== item.i);
    ElMessage.success('卡片已删除');
  } catch (error) {
    console.log('取消删除');
  }
};

const addNewCard = async () => {
  const newId = generateNewId();
  const newCard = {
    x: 0,
    y: findLowestY(),
    w: 4,
    h: 4,
    i: newId,
    remark: `新卡片 ${newId}`,
    page: currentPage.value,
    statedel: '0'
  };

  try {
    const res = await addLayoutConfig(newCard);
    newCard.id = res.data.id;
    layoutItems.value = [...layoutItems.value, newCard];
    ElMessage.success('卡片添加成功');
  } catch (error) {
    console.error('添加卡片失败:', error);
    ElMessage.error('添加卡片失败');
  }
};

const saveCurrentLayout = async () => {
  try {
    isSaving.value = true;
    await batchUpdateLayoutConfig(layoutItems.value);
    ElMessage.success('布局保存成功');
  } catch (error) {
    console.error('保存布局失败:', error);
    ElMessage.error('保存布局失败');
  } finally {
    isSaving.value = false;
  }
};

// 工具方法
const generateNewId = () => {
  const ids = layoutItems.value.map(item => parseInt(item.i)).filter(Number.isInteger);
  return String(Math.max(0, ...ids) + 1);
};

const findLowestY = () => {
  return layoutItems.value.reduce((maxY, item) => Math.max(maxY, item.y + item.h), 0);
};
</script>

<style scoped>
.layout-container {
  position: relative;
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
  font-family: "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}

.page-selector {
  margin-bottom: 20px;
}

.selector-card {
  background: linear-gradient(135deg, #ffffff, #f5f7fa);
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.selector-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
}

.selector-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-right: 16px;
}

.save-btn {
  background: #409EFF;
  border: none;
  transition: all 0.3s;
}

.save-btn:hover {
  background: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.view-mode-selector {
  margin-bottom: 16px;
}

.grid-layout {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 16px;
  min-height: 400px;
}

.item-card {
  height: 100%;
  transition: all 0.3s ease;
  overflow: hidden;
  border: none;
}

.item-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
}

.item-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.item-content {
  padding: 16px;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.info-tag {
  border-radius: 4px;
  padding: 2px 6px;
}

.position-tag {
  display: flex;
  align-items: center;
  background: #f0f2f5;
  color: #606266;
}

.static-item {
  background: #f0f4f8;
  border: 1px dashed #b4bccc;
}

.visible-item {
  background: #b3b3b3;
}

.hidden-item {
  background: #f5f7fa;
  opacity: 0.8;
  border: 1px dashed #dcdfe6;
}

.hidden-item .item-title {
  color: #909399;
}

.empty-layout {
  background: #fff;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.add-card-btn {
  position: fixed;
  right: 40px;
  bottom: 40px;
  z-index: 1000;
  width: 60px;
  height: 60px;
  background: #409EFF;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
  transition: all 0.3s;
  border: none;
}

.add-card-btn:hover {
  transform: scale(1.1) rotate(90deg);
  background: #66b1ff;
}

/* 拖拽相关样式 */
.vue-grid-item:not(.vue-grid-placeholder) {
  transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.vue-grid-item.vue-draggable-dragging {
  z-index: 1001;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  opacity: 0.95;
}

.vue-grid-item.resizing {
  opacity: 0.9;
  z-index: 1000;
}

.vue-grid-placeholder {
  background: #e6f7ff !important;
  border: 2px dashed #1890ff !important;
  border-radius: 8px;
  transition: all 0.3s;
}

/* 适配手机 */
@media (max-width: 768px) {
  .selector-content {
    flex-direction: column;
    align-items: stretch;
  }

  .item-actions {
    flex-direction: column;
  }

  .add-card-btn {
    right: 20px;
    bottom: 20px;
  }
}
</style>